var URLParameters = {};
var yidong_appId = 4;
var yidong_userId;
var yidong_cpId;
var yidong_cpServiceId;
var yidong_channelId;
var yidong_confirmId;
var BuyType;
var hasGetChargeInfo = false;
var hasGetUserInfo = false;
var backDomain = "http://127.0.0.1:8080/";
var yidongDomain = "http://127.0.0.1:8082/";
var chargeDiamongArray = [];

/**
 * 取得查询字符串参数
 * 例：假设查询字符串是?q=javascript&num=10
 * var args=getQueryStringArgs();
 * alert(args["q"]);
 * alert(args["num"]);
 */
function getQueryStringArgs() {
    //取得查询字符串并去掉开头的问号
    var qs = (location.search.length > 0 ? location.search.substring(1) : "");
    //取得每一项
    var items = qs.split("&");
    var item = null,
        name = null,
        value = null;

    //逐个将每一项添加到args对象中
    for (var i = 0; i < items.length; i++) {
        item = items[i].split("=");
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        URLParameters[name] = value;
    }
}

/**
 * 对getQueryStringArgs()方法进行进一步封装，简化调用
 */
function getParameter(keyValue) {
    if (URLParameters[keyValue] != undefined) {
        return URLParameters[keyValue];
    } else {
        return "";
    }
}

Number.prototype.clamp = function(min, max) {
  return Math.min(Math.max(this, min), max);
};

function randomNextInt(lowerValue, upperValue){
    var choices = upperValue - lowerValue + 1;
    return Math.floor(Math.random()*choices + lowerValue);
}


/**
 * 按长度分割字符串
 * @param source_str
 * @param width
 * @param flag
 * @return
 */
function splitString(source_str, width, flag, fontsize, drawCanvas, width_height) {
    drawCanvas.font = fontsize+"px Arial";
    var temp_str = new Array();
    var temp = new Array();
    var maxWidth = 0;
    var height = 0;
    var start = 0;
    for (var i = 1; i < source_str.length + 1; i++) {
        if (drawCanvas.measureText(source_str.substring(start, i - start)).width  > width) {
            temp.push(source_str.substring(start, i - 1));
            start = i - 1;
        } else if (source_str.charAt(i - 1) == flag) {
            temp.push(source_str.substring(start, i - 1));
            start = i;
        }
        if (i == source_str.length) {
            temp.push(source_str.substring(start, i));
            break;
        }
    }
    for (var i = 0; i < temp.length; i++){
        maxWidth = getMaxWidth(drawCanvas.measureText(temp[i]).width, maxWidth);
        height = height + fontsize;
    }
    if(width_height != null){
        width_height[0] = maxWidth;
        width_height[1] = height;
    }
    return temp;
}

function getMaxWidth(strWidth, maxWidth){
    if(strWidth > maxWidth){
        maxWidth = strWidth;
    }
    return maxWidth;
}

function drawStringArray(drawCanvas, strs, startX, startY, anchor, fontsize, textColor){
    var y = startY;
    drawCanvas.font = fontsize+"px Arial";
    drawCanvas.textAlign = anchor;
    drawCanvas.textBaseline = "top";
    drawCanvas.fillStyle = textColor;

    for (var i = 0; i < strs.length; i++) {
        drawCanvas.fillText(strs[i], startX, y);
        y = y + fontsize;
    }

    drawCanvas.font = "14px Arial";
}

/**
 * 绘制带边框圆角矩形
 * @param drawCanvas
 * @param thickness  边框线宽
 * @param lineColor  边框线颜色
 * @param x
 * @param y
 * @param width
 * @param height
 * @param arc
 * @param isfill  是否填充
 * @param fillcolor 填充颜色
 */
function drawRoundRect(drawCanvas, thickness, lineColor, x, y, width, height, arc, isfill, fillcolor){
    if(isfill){
        drawRoundRectBase(drawCanvas, x, y, width, height, arc, true, fillcolor);
    }
    for (var i = 0; i < thickness; i++) {
        drawRoundRectBase(drawCanvas, x+i, y+i, width-i-i, height-i-i, arc, false, lineColor);
    }
}

function drawRoundRectBase(drawCanvas, x, y, w, h, r, needFill, color) {
    if (w < 2 * r) r = w / 2;
    if (h < 2 * r) r = h / 2;

    drawCanvas.beginPath();
    drawCanvas.moveTo(x+r, y);
    drawCanvas.arcTo(x+w, y, x+w, y+h, r);
    drawCanvas.arcTo(x+w, y+h, x, y+h, r);
    drawCanvas.arcTo(x, y+h, x, y, r);
    drawCanvas.arcTo(x, y, x+w, y, r);
// this.arcTo(x+r, y);
    drawCanvas.closePath();
    if(needFill){
        drawCanvas.fillStyle = color;
        drawCanvas.fill();
    }
    else{
        drawCanvas.strokeStyle = color;
        drawCanvas.stroke();
    }
}

function drawRound(color,startX,startY,sradius,startJiaodu,endJiaodu,shushizhen){
    canvas.fillStyle=color;
    canvas.beginPath();
    canvas.arc( startX,startY,sradius,startJiaodu,endJiaodu,shushizhen);
    canvas.closePath();
    canvas.fill();
}

function clipDrawFrame(sourceImg, cutX, cutY, screenX, screenY, cutWidth, cutHeight, drawCanvas) {
    if(cutWidth == 0 || cutHeight == 0){
        return;
    }
    drawCanvas.drawImage(sourceImg, cutX, cutY, cutWidth, cutHeight, screenX, screenY, cutWidth, cutHeight);
}

function drawFrame(sourceImg, frameCount, x, y, width, height, row, drawCanvas) {
    drawCanvas.drawImage(sourceImg, frameCount*width, row*height, width, height, x, y, width, height);
}

function checkNumLength(num, letterWidth){
    var count = 0;
    if (num < 10) {
        count = 1;
    } else if (num >= 10 && num < 100) {
        count = 2;
    } else if (num >= 100 && num < 1000) {
        count = 3;
    } else if (num >= 1000 && num < 10000) {
        count = 4;
    }  else if (num >= 10000 && num < 100000) {
        count = 5;
    }
    else if (num >= 100000 && num < 1000000) {
        count = 6;
    }
    else if (num >= 1000000 && num < 10000000) {
        count = 7;
    }
    else if (num >= 10000000 && num < 100000000) {
        count = 8;
    }
    else if (num >= 100000000 && num < 1000000000) {
        count = 9;
    }
    else{
        count = 9;
    }
    return count*letterWidth;
}

function drawNum(drawCanvas, num, x, y, w, h, im) {
    if (num < 10) {
        drawFrame(im, num, x, y, w, h, 0, drawCanvas);
    } else if (num >= 10 && num < 100) {
        drawFrame(im, zhengchu(num,10), x, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 10, x + w, y, w, h, 0, drawCanvas);
    } else if (num >= 100 && num < 1000) {
        drawFrame(im, zhengchu(num,100), x, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100,10), x + w, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 100 % 10, x + w * 2, y, w, h, 0, drawCanvas);
    } else if (num >= 1000 && num < 10000) {
        drawFrame(im, zhengchu(num,1000), x, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000,100), x + w, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100,10), x + w * 2, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 1000 % 100 % 10, x + w * 3, y, w, h, 0, drawCanvas);
    }  else if (num >= 10000 && num < 100000) {
        drawFrame(im, zhengchu(num,10000), x, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000,1000), x + w, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000,100), x + w * 2, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100,10), x + w * 3, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 10000 % 1000 % 100 % 10, x + w * 4, y, w, h, 0, drawCanvas);
    }
    else if (num >= 100000 && num < 1000000) {
        drawFrame(im, zhengchu(num,100000), x, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100000,10000), x + w, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000,1000), x + w * 2, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000,100), x + w * 3, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100,10), x + w * 4, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 100000 % 10000 % 1000 % 100 % 10, x + w * 5, y, w, h, 0, drawCanvas);
    }
    else if (num >= 1000000 && num < 10000000) {
        drawFrame(im, zhengchu(num,1000000), x, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000000,100000), x + w, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100000,10000), x + w * 2, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000,1000), x + w * 3, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000,100), x + w * 4, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100,10), x + w * 5, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 1000000 % 100000 % 10000 % 1000 % 100 % 10, x + w * 6, y, w, h, 0, drawCanvas);
    }
    else if (num >= 10000000 && num < 100000000) {
        drawFrame(im, zhengchu(num,10000000), x, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000000,1000000), x + w, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000000,100000), x + w * 2, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100000,10000), x + w * 3, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000,1000), x + w * 4, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000,100), x + w * 5, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100,10), x + w * 6, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 10000000 % 1000000 % 100000 % 10000 % 1000 % 100 % 10, x + w * 7, y, w, h, 0, drawCanvas);
    }
    else if (num >= 100000000 && num < 1000000000) {
        drawFrame(im, zhengchu(num,100000000), x, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100000000,10000000), x + w, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000000,1000000), x + w * 2, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000000,100000), x + w * 3, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100000,10000), x + w * 4, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000,1000), x + w * 5, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000,100), x + w * 6, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100,10), x + w * 7, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 100000000 % 10000000 % 1000000 % 100000 % 10000 % 1000 % 100 % 10, x + w * 8, y, w, h, 0, drawCanvas);
    }
    else{
        num = 999999999;
        drawFrame(im, zhengchu(num,1000000000), x, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100000000,10000000), x + w, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000000,1000000), x + w * 2, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000000,100000), x + w * 3, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100000,10000), x + w * 4, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 10000,1000), x + w * 5, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 1000,100), x + w * 6, y, w, h, 0, drawCanvas);
        drawFrame(im, zhengchu(num % 100,10), x + w * 7, y, w, h, 0, drawCanvas);
        drawFrame(im, num % 100000000 % 10000000 % 1000000 % 100000 % 10000 % 1000 % 100 % 10, x + w * 8, y, w, h, 0, drawCanvas);
    }
}



var EventUtil = {
    addHandler:function(element, type, handler){
        if(element.addEventListener){
            element.addEventListener(type, handler, false);
        }
        else if(element.attachEvent){
            element.attachEvent("on"+type, handler);
        }
        else{
            element["on"+type] = handler;
        }
    },
    getEvent:function(event){
        return event?event:window.event;
    },
    getTarget:function(event){
        return event.target||event.srcElement;
    },
    preventDefault:function(event){
        if(event.preventDefault){
            event.preventDefault();
        }
        else{
            event.returnValue = false;
        }
    },
    removeHandler:function(element, type, handler){
        if(element.removeEventListener){
            element.removeEventListener(type, handler, false);
        }
        else if(element.detachEvent){
            element.detachEvent("on"+type, handler);
        }
        else{
            element["on"+type] = null;
        }
    },
    stopPropagation:function(event){
        if(event.stopPropagation){
            event.stopPropagation();
        }
        else{
            event.cancelBubble = true;
        }
    },
    getRelatedTarget:function(event){
        if(event.relatedTarget){
            return event.relatedTarget;
        }
        else if(event.toElement){
            return event.toElement;
        }
        else if(event.fromElement){
            return event.fromElement;
        }
        else{
            return null;
        }
    },
    getButton:function(event){
        if(document.implementation.hasFeature("MouseEvents", "2.0")){
            return event.button;
        }
        else{
            switch(event.button){
                case 0:
                case 1:
                case 3:
                case 5:
                case 7:
                    return 0;
                case 2:
                case 6:
                    return 2;
                case 4:
                    return 1;
            }
        }
    },
    getWheelDelta:function(event){
        if(event.wheelDelta){
            return (client.engine.opera && client.engine.opera < 9.5 ? -event.wheelDelta:event.wheelDelta);
        }
        else{
            return -event.wheelDelta*40;
        }
    }

}


var startTime;
var CycleTime = 40;
window.requestAFrame = (function () {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        // if all else fails, use setTimeout
        function (callback) {
            return window.setTimeout(callback, CycleTime); // shoot for 60 fps
        };
})();
// handle multiple browsers for cancelAnimationFrame()
window.cancelAFrame = (function () {
    return window.cancelAnimationFrame ||
        window.webkitCancelAnimationFrame ||
        window.mozCancelAnimationFrame ||
        window.oCancelAnimationFrame ||
        window.msCancelAnimationFrame  ||
        function (id) {
            window.clearTimeout(id);
        };
})();

//整除，相当于java中的/
function zhengchu(temp1,temp2){
    return Math.floor(temp1/temp2);
}

//32位整数最大值
Number.MY_MAX_VALUE = Math.pow(2,31)-1;

//用于继承父类
function object(o){
    function F(){};
    F.prototype = o;
    return new F();
}
function inheritPrototype(subType, superType){
    var prototype = object(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}

function getDeviceConfig() {
    return navigator.userAgent.toLowerCase().indexOf("iphone") != -1 || navigator.userAgent.toLowerCase().indexOf("ipod") != -1 ? {device: "iphone", fps: 1, touch: true, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("maiandroid") != -1 ? {device: "maiAndroid", fps: 1, touch: true, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("maiwindowsphone") != -1 ? {device: "maiWindowsPhone", fps: 1, touch: true, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("android") != -1 ? {device: "android", fps: 1, touch: true, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("ipad") != -1 ? {device: "ipad", fps: 1, touch: true, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("j2me") != -1 ? {device: "j2me", fps: 1, touch: false, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("symbian v5") != -1 ? {device: "symbian5", fps: 1, touch: true, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("symbian v3") != -1 ? {device: "symbian3", fps: 1, touch: false, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("chrome") != -1 ? {device: "chrome", fps: 1, touch: false, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("msie") != -1 ? {device: "ie", fps: 0.5, touch: false, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("safari") != -1 ? {device: "safari", fps: 1, touch: false, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("opera") != -1 ? {device: "opera", fps: 1, touch: false, zoom: 1} : navigator.userAgent.toLowerCase().indexOf("gecko") != -1 ? {device: "firefox",
        fps: 1, touch: false, zoom: 1} : {device: "", fps: 1, touch: false, zoom: 1}
}

//获取设备是否支持触屏
var deviceTouchable = (function checkForTouch() {
    try {
        var a = document.createElement("div");
        a.setAttribute("ontouchmove", "return;");
        return"function" === typeof a.ontouchmove ? true : false
    } catch (b) {
        return false;
    }
})();

//检查2个矩形是否相交
function rectCollisionCheck(x1,y1,w1,h1, x,y,w,h){
    if(x1>x-w1 && x1<x+w && y1>y-h1 && y1<y+h){
        return true;
    }
    else{
        return false;
    }
}

function isTouch_inArea(px, py, left, top, right, bottom) {
    if (px > left && px < right) {
        if (py < bottom && py > top) {
            return true;
        }
        return false;
    }
    return false;
}

//计算指向性子弹x，y速度
function getDirectSpeedXY(tempPlaneCenterPX, tempPlaneCenterPY, enermyCenterPX, enermyCenterPY, baseSpeed){
    var speedX,speedY;
    if(tempPlaneCenterPX == enermyCenterPX){
        speedX = 0;
        if(tempPlaneCenterPY > enermyCenterPY){
            speedY = baseSpeed;
        }
        else{
            speedY = -baseSpeed;
        }
    }
    else if(tempPlaneCenterPY == enermyCenterPY){
        if(tempPlaneCenterPX > enermyCenterPX){
            speedX = baseSpeed;
        }
        else{
            speedX = -baseSpeed;
        }
        speedY = 0;
    }
    else{
        var YXscale = Math.abs(enermyCenterPY - tempPlaneCenterPY) / Math.abs(enermyCenterPX - tempPlaneCenterPX);
        speedX = Math.sqrt(baseSpeed*baseSpeed/(YXscale*YXscale+1));
        speedY = speedX*YXscale;
        if(tempPlaneCenterPX < enermyCenterPX){
            speedX = -speedX;
        }
        if(tempPlaneCenterPY < enermyCenterPY){
            speedY = -speedY;
        }
    }
    var tempArray = new Array();
    tempArray.push(speedX);
    tempArray.push(speedY);
    return tempArray;
}

//音频处理
var AUDIO = false;//是否支持声音
var SoundEnable = true;//是否开启声音
var gamedata = {audioFiles: "titlemusic shot explode4 explode5 explode6 toolcatch".split(" ")};
var m = {audio: {}};
var audioContext;
var AUDIOFORMAT = "mp3";
//初始化
(function setAudio() {
    //try {
        var a = document.createElement("audio");
         audioContext= new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
         console.log(audioContext);
    AUDIO = true;
    SoundEnable = true;
})();
function loadSound(a) {
    try {
        var b = new XMLHttpRequest, d = "sounds/" + a.soundname +"."+ AUDIOFORMAT;
        b.open("GET", d, !0);
        b.responseType = "arraybuffer";
        b.onload = function () {
            try {
                audioContext.decodeAudioData(b.response, function (buffer) {//解码成功调用
                        a.buffer = buffer;
                        a.volume = "titlemusic" == a.soundname ? 0.6 : 0.4
                        loadProgress();
                }, function (a) {
                        loadProgress();
                    }//解码失败调用
                )
            } catch (c) {
            }
        };
        b.send()
    } catch (c) {
        console.log("loadSound error");
    }
}
function preCache() {
    if (AUDIO) {
        for (var a = 0; a < gamedata.audioFiles.length; a++){
            m.audio[gamedata.audioFiles[a]] = {source: null, count: 0, gainNode: null, soundname: gamedata.audioFiles[a]}, loadSound(m.audio[gamedata.audioFiles[a]])
        }
        return gamedata.audioFiles.length;
    }
    else{
        return 0;
    }

}
function check() {
};

//播放一次
function sfx(a) {
    if (AUDIO && SoundEnable) {
        try {
            var b = m.audio[a], c = audioContext.createBufferSource(), d = audioContext.createGain();
            c.buffer = b.buffer;
            c.loop = !1;
            c.connect(d);
            d.connect(audioContext.destination);
            d.gain.value = b.volume;
            c.start(0);
           // c.noteOn(0);
        } catch (e) {
            console.log("sfx: " + e.message);

        }
    }
};
//循环播放
function setSoundtrack() {
    if (AUDIO && SoundEnable) {
        try {
            var a = m.audio.titlemusic;
            if(a&& !a.playing){
                a.source = audioContext.createBufferSource();
                    a.gainNode = audioContext.createGain();
                    a.source.buffer = a.buffer;
                    a.source.loop = !0;
                    a.source.connect(a.gainNode);
                    a.gainNode.connect(audioContext.destination);
                    a.gainNode.gain.value = a.volume;
                   // a.source.noteOn(0);
                    a.source.start(0);
                    a.playing = !0;
            }
        } catch (b) {
            console.log("SetSoundtrack: " + b.message)
        }
    }
}

function musicMode() {
    var b = m.audio.titlemusic;
    if(!SoundEnable){
        b.gainNode.gain.value = 0;
    }
    else{
        b.gainNode.gain.value = b.volume;
    }
}





function initYIDONGParamater(){
    getQueryStringArgs();
    yidong_userId = getParameter("userId");
    if(null == yidong_userId || yidong_userId==""){
        yidong_userId = "test";
    }
    yidong_cpId = getParameter("cpId");
    yidong_cpServiceId = getParameter("cpServiceId");
    yidong_channelId = getParameter("channelId");
}

function getUserInfo(){
    if(!hasGetChargeInfo){
        getFeeCode();
        return false;
    }
    if(!hasGetUserInfo){
        checkAuth();
        return false;
    }
    return true;
}

function getFeeCode(){
    loading4JS.showLoading("正在读取个人数据，请等待！");

    $.ajax({
        type: "POST",
        url: yidongDomain+"H5Agent/Fee",
        cache: false,
        dataType: "jsonp",
        jsonp: "callback",
        data: "NType=get_recharge_list&appId="+yidong_appId,
        success: function(result){
            for(var i=0;i<result.length;i++){
                var tempArr = [];
                tempArr[0] = result[i].rechargeNumber;
                tempArr[1] = result[i].extendation;
                tempArr[2] = result[i].feeCode;
                chargeDiamongArray.push(tempArr);
            }

            hasGetChargeInfo = true;
            loading4JS.closeLoading();
            getUserInfo();
        },
        error: function(){
            hasGetChargeInfo = false;
            toast4JS.buildToast("读取失败，请重试！",1500);
            loading4JS.closeLoading();
        }
    });
}

function checkAuth(){
    loading4JS.showLoading("正在读取个人数据，请等待！");
    myAjax(backDomain+"airwarback/getinfo",{userId:yidong_userId},function(res){
        if(res.code == "0"){
            var userObj = res.user;
            if(userObj.newer == 1){
                isNewPlayer = true;
            }
            else{
                isNewPlayer = false;
            }

            if(userObj.haslottochance == 1){
                hasLottoChance = true;
            }
            else{
                hasLottoChance = false;
            }

            driverIndex = fightDriverIndex = userObj.fight_index;

            myCoin =userObj.coin;
            myDiamond =userObj.diamond;
            myMaxScore =userObj.max_score;

            //驾驶员名字
            createDriverNames();
            var str_name_index =userObj.name_index;
            var str_name_changeable =userObj.name_changeable;
            hasChooseNameArray = str_name_changeable.split(",");
            driverNameIndex = str_name_index.split(",");
            for(var i=0;i<hasChooseNameArray.length;i++){
                if(hasChooseNameArray[i] == "1"){
                    hasChooseNameArray[i] = false;
                }
                else{
                    hasChooseNameArray[i] = true;
                }
                driverNameIndex[i] = parseInt(driverNameIndex[i]);
                if(hasChooseNameArray[i]){
                    driverName[i] = DriverNameArray[i][driverNameIndex[i]];
                }
                else{
                    driverName[i] = DriverNameArray[i][0];
                }
            }

            //战机等级
            var str_plane_level = userObj.plane_level;
            myPlaneLevel = str_plane_level.split(",");
            for(var i=0;i<myPlaneLevel.length;i++){
                myPlaneLevel[i] = parseInt(myPlaneLevel[i]);
                myFightAttack[i] = 5000 + (myPlaneLevel[i]-1)*500;
            }

            //宠物等级
            var str_pet_level = userObj.pet_level;
            animLevelArray = str_pet_level.split(",");
            for(var i=0;i<animLevelArray.length;i++){
                animLevelArray[i] = parseInt(animLevelArray[i]);
                animAttackArray[i] = i+animLevelArray[i];
            }

            //材料数组
            var str_material_array = userObj.material_array;
            myMaterialArray = str_material_array.split(",");
            for(var i=0;i<myMaterialArray.length;i++){
                myMaterialArray[i] = parseInt(myMaterialArray[i]);
            }

            //道具数组
            var str_tool_array = userObj.tool_array;
            myToolArray = str_tool_array.split(",");
            for(var i=0;i<myToolArray.length;i++){
                myToolArray[i] = parseInt(myToolArray[i]);
            }

            //关卡解锁情况
            var str_mission_unlock =userObj.mission_unlock;
            MissionUnlock = str_mission_unlock.split(",");
            for(var i=0;i<MissionUnlock.length;i++){
                if(MissionUnlock[i] == "1"){
                    MissionUnlock[i] = true;
                }
                else{
                    MissionUnlock[i] = false;
                }
            }
            //黑暗等级
            currentBlackStage = userObj.black_level;
            if(userObj.black_unlock == 1){
                isBlackStateUnlock = true;
            }
            else{
                isBlackStateUnlock = false;
            }

            loading4JS.closeLoading();
            hasGetUserInfo = true;
            changeState(6);
        }
        else{
            loading4JS.closeLoading();
            hasGetUserInfo = false;
            toast4JS.buildToast("读取失败，请重试！",1500);
        }
    },function(){
        loading4JS.closeLoading();
        hasGetUserInfo = false;
        toast4JS.buildToast("读取失败，请重试！",1500);
    });
}

//移动扣费
function openChargePage(){
    $("#errormsg").find("p").html("").end().show();
    $("#confirm").show();
    $("#getconfirm").show();
    $("#getconfirm").find("p").html("正在获取验证码，请稍等。。。");
    $("#getconfirm_l_retry").hide();
    $("#getconfirm_l_cancel").hide();

    $("#tipmsg").find("strong").html(chargeDiamongArray[BuyType][1]);

    getImgCode(chargeDiamongArray[BuyType][2]);
}

function confirmCancel(){
    $("#confirm").hide();
    $("#getconfirm").hide();
}
function retryGetImg(){
    $("#getconfirm").find("p").html("正在获取验证码，请稍等。。。");
    $("#getconfirm_l_retry").hide();
    $("#getconfirm_l_cancel").hide();

    getImgCode(chargeDiamongArray[BuyType][2]);
}

//var confirmId = "";
function confirmSubmitCode(){
    var verify = $("#verify").val();
    if(verify == '' || verify == "验证码"){
        $("#errormsg").find("p").html("请输入验证码").end().show();
        return false;
    }

    $("#getconfirm").show();
    $("#getconfirm").find("p").html("正在验证信息，请稍等。。。");
    $("#getconfirm_l_retry").hide();
    $("#getconfirm_l_cancel").hide();

    $.ajax({
        type: "POST",
        url: yidongDomain+"H5Agent/Fee",
        cache: false,
        dataType: "jsonp",
        jsonp: "callback",
        data:"NType=pay_confirm&confirmId="+yidong_confirmId+"&answer="+verify+"&appId="+yidong_appId,
        success: function(result){
            if (result.status == 100000) {
                confirmCancel();

                loading4JS.showLoading("正在提交请求，请等待！");
                myDiamond = myDiamond + chargeDiamongArray[BuyType][0];

                updateBaseInfo(function(){
                    loading4JS.closeLoading();
                    toast4JS.buildToast("充值成功！",1500);
                });
            }else{
                confirmCancel();
                toast4JS.buildToast("充值失败！", 1500);
            }
        },
        error: function(){
            confirmCancel();
            toast4JS.buildToast("充值失败！", 1500);
        }
    });
}
function refreshImage()
{
    $("#getconfirm").show();
    retryGetImg();
}

function clearVerify(object){
    object.value = "";
}

function getImgCode(rechargeId){
    $.ajax({
        type: "POST",
        url: yidongDomain+"H5Agent/Fee",
        cache: false,
        dataType: "jsonp",
        jsonp: "callback",
        data:"NType=get_recharge_image&cpId="+yidong_cpId+"&cpServiceId=648916026407"+"&feeCode="+rechargeId+"&channelId="+yidong_channelId+"&appId="+yidong_appId+"&userId="+yidong_userId,
        success: function(result){
            if (result.status == 100000) {
                yidong_confirmId = result.confirmId;
                $("#confirm_img").attr("src",result.picVCodeURL);
                $("#getconfirm").hide();
            }else{
                $("#getconfirm_tip").find("p").html("获取验证码失败！");
                $("#getconfirm_l_retry").show();
                $("#getconfirm_l_cancel").show();
            }
        },
        error: function(){
            console.log("error");
        }
    });
}

function userRegister(){
    $.ajax({
        type: "POST",
        url: yidongDomain+"H5Agent/Fee",
        cache: false,
        dataType: "jsonp",
        jsonp: "callback",
        data:"NType=register&cpId="+yidong_cpId+"&cpServiceId="+yidong_cpServiceId+"&channelId="+yidong_channelId+"&appId="+yidong_appId+"&userId="+yidong_userId,
        success: function(result){
        },
        error: function(){
        }
    });
}


function myAjax(url,data,successFuc,failFuc,context){
    var context  = context||this;
    $.ajax({
        url:url,
        type:"POST",
        data:data,
        async : true, //默认为true 异步
        cache: false,
        dataType: "jsonp",
        jsonp: "callback",
        error:function(res){
            if(failFuc){
                failFuc.call(context, res)
            }
        },
        success:function(res){
            if(successFuc){
                successFuc.call(context, res);
            }
        }
    });
}


function updateBaseInfo(successFuc){
    myAjax(backDomain+"airwarback/updatebase",{userId:yidong_userId,coin:myCoin,diamond:myDiamond,maxScore:myMaxScore},successFuc);
}

function updateFightPlayer(successFuc){
    myAjax(backDomain+"airwarback/updatefightplayer",{userId:yidong_userId,fightIndex:fightDriverIndex},successFuc);
}

function UpdatePlayer(successFuc){
    var nameIndexStr = "";
    for(var i=0;i<driverNameIndex.length;i++){
        if(i>0){
            nameIndexStr = nameIndexStr + ",";
        }
        nameIndexStr = nameIndexStr+driverNameIndex[i];
    }

    var nameChangeableStr = "";
    for(var i=0;i<hasChooseNameArray.length;i++){
        if(i>0){
            nameChangeableStr = nameChangeableStr + ",";
        }
        if(hasChooseNameArray[i]){
            nameChangeableStr = nameChangeableStr+0;
        }
        else{
            nameChangeableStr = nameChangeableStr+1;
        }
    }

    myAjax(backDomain+"airwarback/updateplayer",{userId:yidong_userId,nameIndex:nameIndexStr,nameChangeable:nameChangeableStr},successFuc);
}


function UpdatePlaneLevel(successFuc){
    var planeLevelStr = "";
    for(var i=0;i<myPlaneLevel.length;i++){
        if(i>0){
            planeLevelStr = planeLevelStr + ",";
        }
        planeLevelStr = planeLevelStr+myPlaneLevel[i];
    }

    var materialArrayStr = "";
    for(var i=0;i<myMaterialArray.length;i++){
        if(i>0){
            materialArrayStr = materialArrayStr + ",";
        }
        materialArrayStr = materialArrayStr+myMaterialArray[i];
    }

    myAjax(backDomain+"airwarback/updateplane",{userId:yidong_userId,coin:myCoin,diamond:myDiamond,planeLevel:planeLevelStr,materialArray:materialArrayStr},successFuc);
}

function UpdatePetLevel(successFuc){
    var petLevelStr = "";
    for(var i=0;i<animLevelArray.length;i++){
        if(i>0){
            petLevelStr = petLevelStr + ",";
        }
        petLevelStr = petLevelStr+animLevelArray[i];
    }

    var materialArrayStr = "";
    for(var i=0;i<myMaterialArray.length;i++){
        if(i>0){
            materialArrayStr = materialArrayStr + ",";
        }
        materialArrayStr = materialArrayStr+myMaterialArray[i];
    }

    myAjax(backDomain+"airwarback/updatepet",{userId:yidong_userId,coin:myCoin,diamond:myDiamond,petLevel:petLevelStr,materialArray:materialArrayStr},successFuc);
}

function UpdateTool(successFuc){
    var toolArrayStr = "";
    for(var i=0;i<myToolArray.length;i++){
        if(i>0){
            toolArrayStr = toolArrayStr + ",";
        }
        toolArrayStr = toolArrayStr+myToolArray[i];
    }

    var hasLottoChanceInt;
    if(hasLottoChance){
        hasLottoChanceInt = 1;
    }
    else{
        hasLottoChanceInt = 0;
    }

    myAjax(backDomain+"airwarback/updatetool",{userId:yidong_userId,coin:myCoin,diamond:myDiamond,toolArray:toolArrayStr,hasLottoChance:hasLottoChanceInt},successFuc);
}

function UpdateTotal(successFuc){
    var materialArrayStr = "";
    for(var i=0;i<myMaterialArray.length;i++){
        if(i>0){
            materialArrayStr = materialArrayStr + ",";
        }
        materialArrayStr = materialArrayStr+myMaterialArray[i];
    }

    var toolArrayStr = "";
    for(var i=0;i<myToolArray.length;i++){
        if(i>0){
            toolArrayStr = toolArrayStr + ",";
        }
        toolArrayStr = toolArrayStr+myToolArray[i];
    }

    var missionUnlockStr = "";
    for(var i=0;i<MissionUnlock.length;i++){
        if(i>0){
            missionUnlockStr = missionUnlockStr + ",";
        }
        if(MissionUnlock[i]){
            missionUnlockStr = missionUnlockStr+1;
        }
        else{
            missionUnlockStr = missionUnlockStr+0;
        }
    }

    var blackUnlockInt;
    if(isBlackStateUnlock){
        blackUnlockInt = 1;
    }
    else{
        blackUnlockInt = 0;
    }

    myAjax(backDomain+"airwarback/updatetotal",{userId:yidong_userId,coin:myCoin,diamond:myDiamond,maxScore:myMaxScore,materialArray:materialArrayStr,toolArray:toolArrayStr,missionUnlock:missionUnlockStr,blackLevel:currentBlackStage,blackUnlock:blackUnlockInt},successFuc);
}



